package com.ayf.payment.game.api.wx;


import com.alibaba.fastjson.JSON;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.entity.platform.WxConfig;
import com.ayf.payment.game.api.exception.LogicalException;
import com.ayf.payment.game.api.exception.WxException;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 常用
 * @Author: zh-liang
 */
@Component
public class MyConstant {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    /**
     * 获取 access_token
     *
     * @return ACCESS_TOKEN
     */
    public String getAccessToken(WxConfig wxConfig) {
        //判断ACCESS_TOKEN是否为空，或者ACCESS_TOKEN_TIME是否超时
        String ACCESS_TOKEN = redisCacheUtil.getObjectFromCache("GAME_PAY_WX_CONFIG:PLATFORM_WX_ACCESS_TOKEN");
        if (StringUtils.isBlank(ACCESS_TOKEN)) {
            LogPortal.info("获取access_token请求参数:【{}】", JSON.toJSONString(wxConfig));
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getAppSecret();
            JSONObject jsonObject = WxHttpUtil.doGet("获取access_token",url);
            LogPortal.info("获取access_token返回【{}】", jsonObject);
            if (jsonObject == null) {
                throw new WxException("调用微信接口网络错误，请稍后重试");
            }
            if (jsonObject.has("errcode")) {
                throw new WxException("平台微信公众号Appid或公众号Secrt配置错误");
            }
            //设置ACCESS_TOKEN
            ACCESS_TOKEN = jsonObject.get("access_token").toString();
            redisCacheUtil.setObjectToCache("GAME_PAY_WX_CONFIG:PLATFORM_WX_ACCESS_TOKEN", ACCESS_TOKEN, 7100L, TimeUnit.SECONDS);
        }
        return ACCESS_TOKEN;
    }

    /**
     * 获取模板id
     *
     * @param wxConfig
     * @param templateIdShort
     * @return
     */
    public String getTemplateId(WxConfig wxConfig, String templateIdShort) {
        String url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + getAccessToken(wxConfig);

        Map<String, Object> map = new HashMap<>();
        map.put("template_id_short", templateIdShort);
        String data = JSON.toJSONString(map);
        try {
            JSONObject jsonObject = WxHttpUtil.doPost(("获取模板id".concat(templateIdShort)),url, data);
            String errmsg = jsonObject.getString("errmsg");
            String templateId = jsonObject.getString("template_id");
            int errcode = jsonObject.getInt("errcode");
            if (errcode == 0 && "ok".equals(errmsg)) {
                LogPortal.info("[{}]获取模板id成功", templateIdShort);
            } else {
                LogPortal.error("[{}]获取模板id失败[{}]", templateIdShort, jsonObject.toString());
            }
            return templateId;
        } catch (Exception e) {
            LogPortal.error("[{}]获取模板id失败,发生{}异常，异常信息为：{}", e, templateIdShort, e.getClass().getSimpleName(), e.getMessage());
            return null;
        }
    }

    /**
     * 无敌助手消息发送
     * @param wxConfig
     * @param wxMsg
     * @return
     */
    public CommonResult sendWdZhuShouMsg(WxConfig wxConfig, WxMsg wxMsg) {
        CommonResult commonResult=new  CommonResult();
        commonResult.setCode(CommonConstants.RETURN_SUCCESS);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(wxConfig);
        Map<String, Object> map = new HashMap<>();
        map.put("touser", wxMsg.getOpenid());
        map.put("template_id", wxMsg.getTemplateId());
        map.put("url", "");

        Map<String, Object> miniMap = new HashMap<>();
        miniMap.put("appid", "");
        miniMap.put("pagepath", "");
        map.put("miniprogram", miniMap);

        Map<String, Object> dataMap = new HashMap<>();

        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("value", wxMsg.getFirst());
        firstMap.put("color", "#FA0E30");
        dataMap.put("first", firstMap);

        Map<String, Object> remarkMap = new HashMap<>();
        remarkMap.put("value", wxMsg.getRemark());
        remarkMap.put("color", "#FA0E30");
        dataMap.put("remark", remarkMap);

        if (StringUtils.isNotBlank(wxMsg.getKeyword1())) {
            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value", wxMsg.getKeyword1());
            keyword1.put("color", "#FA0E30");
            dataMap.put("keyword1", keyword1);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword2())) {
            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value", wxMsg.getKeyword2());
            keyword2.put("color", "#FA0E30");
            dataMap.put("keyword2", keyword2);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword3())) {
            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value", wxMsg.getKeyword3());
            keyword3.put("color", "#FA0E30");
            dataMap.put("keyword3", keyword3);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword4())) {
            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value", wxMsg.getKeyword4());
            keyword4.put("color", "#FA0E30");
            dataMap.put("keyword4", keyword4);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword5())) {

            Map<String, Object> keyword5 = new HashMap<>();
            keyword5.put("value", wxMsg.getKeyword5());
            keyword5.put("color", "#FA0E30");
            dataMap.put("keyword5", keyword5);
        }

        map.put("data", dataMap);

        String data = JSON.toJSONString(map);
        try {
            JSONObject jsonObject = WxHttpUtil.doPost("微信公众号提醒发送".concat(wxMsg.getOpenid()),url, data);
            String errmsg = jsonObject.getString("errmsg");
            int errcode = jsonObject.getInt("errcode");
            if (errcode == 0 && "ok".equals(errmsg)) {
                LogPortal.info("[{}]微信公众号提醒发送成功", wxMsg.getOpenid());
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "发送成功");
            } else {
                LogPortal.error("[{}]微信公众号提醒发送失败[{}]", wxMsg.getOpenid(), jsonObject.toString());
            }
            return new CommonResult<>(CommonConstants.RETURN_ERROR, jsonObject.toString());
        } catch (Exception e) {
            LogPortal.error("微信消息发送失败，发生：{}异常，异常信息为：{}", e, e.getClass().getSimpleName(), e.getMessage());
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "发送失败,异常信息:"+e.getMessage());
        }
    }
    public String sendTemplateMsg(WxConfig wxConfig, WxMsg wxMsg) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(wxConfig);
        Map<String, Object> map = new HashMap<>();
        map.put("touser", wxMsg.getOpenid());
        map.put("template_id", wxMsg.getTemplateId());
        map.put("url", "");

        Map<String, Object> miniMap = new HashMap<>();
        miniMap.put("appid", "");
        miniMap.put("pagepath", "");
        map.put("miniprogram", miniMap);

        Map<String, Object> dataMap = new HashMap<>();

        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("value", wxMsg.getFirst());
        firstMap.put("color", "#173177");
        dataMap.put("first", firstMap);

        Map<String, Object> remarkMap = new HashMap<>();
        remarkMap.put("value", wxMsg.getRemark());
        remarkMap.put("color", "#173177");
        dataMap.put("remark", remarkMap);

        if (StringUtils.isNotBlank(wxMsg.getKeyword1())) {
            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value", wxMsg.getKeyword1());
            keyword1.put("color", "#173177");
            dataMap.put("keyword1", keyword1);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword2())) {
            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value", wxMsg.getKeyword2());
            keyword2.put("color", "#173177");
            dataMap.put("keyword2", keyword2);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword3())) {
            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value", wxMsg.getKeyword3());
            keyword3.put("color", "#173177");
            dataMap.put("keyword3", keyword3);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword4())) {
            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value", wxMsg.getKeyword4());
            keyword4.put("color", "#173177");
            dataMap.put("keyword4", keyword4);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword5())) {
            Map<String, Object> keyword5 = new HashMap<>();
            keyword5.put("value", wxMsg.getKeyword5());
            keyword5.put("color", "#173177");
            dataMap.put("keyword5", keyword5);
        }

        map.put("data", dataMap);

        String data = JSON.toJSONString(map);
        try {
            JSONObject jsonObject = WxHttpUtil.doPost("微信公众号提醒发送".concat(wxMsg.getOpenid()),url, data);
            String errmsg = jsonObject.getString("errmsg");
            int errcode = jsonObject.getInt("errcode");
            if (errcode == 0 && "ok".equals(errmsg)) {
                LogPortal.info("[{}]微信公众号提醒发送成功", wxMsg.getOpenid());
            } else {
                LogPortal.error("[{}]微信公众号提醒发送失败[{}]", wxMsg.getOpenid(), jsonObject.toString());
            }
            return jsonObject.toString();
        } catch (Exception e) {
            LogPortal.error("微信消息发送失败，发生：{}异常，异常信息为：{}", e, e.getClass().getSimpleName(), e.getMessage());
            return null;
        }
    }

    /**
     * 设置菜单
     *
     * @param wxConfig
     * @return
     */
    public boolean setMenu(WxConfig wxConfig) {
        JSONObject big = new JSONObject();
        JSONArray button = new JSONArray();

        try {
            //一级菜单 1
            JSONObject menu_a = new JSONObject();
            menu_a.put("name", "个人中心");
            JSONArray button2 = new JSONArray();

            //二级菜单 1
            JSONObject menu_a_5 = new JSONObject();
            menu_a_5.put("name", "我的账号");
            menu_a_5.put("type", "view");
            String uri5 = URLEncoder.encode(wxConfig.getNetUrl() + "/h5/account", "utf-8");
            menu_a_5.put("url", getAuthorizeUrl(wxConfig.getAppId(), uri5));
            button2.put(menu_a_5);

            //二级菜单 2
            JSONObject menu_a_3 = new JSONObject();
            menu_a_3.put("name", "订单统计");
            menu_a_3.put("type", "view");
            String uri3 = URLEncoder.encode(wxConfig.getNetUrl() + "/h5/order", "utf-8");
            menu_a_3.put("url", getAuthorizeUrl(wxConfig.getAppId(), uri3));
            button2.put(menu_a_3);

            //二级菜单 3
            JSONObject menu_a_4 = new JSONObject();
            menu_a_4.put("name", "开区情况");
            menu_a_4.put("type", "view");
            String uri4 = URLEncoder.encode(wxConfig.getNetUrl() + "/h5/gameConfig", "utf-8");
            menu_a_4.put("url", getAuthorizeUrl(wxConfig.getAppId(), uri4));
            button2.put(menu_a_4);

            //二级菜单 4
            JSONObject menu_a_2 = new JSONObject();
            menu_a_2.put("name", "补发情况");
            menu_a_2.put("type", "view");
            String uri2 = URLEncoder.encode(wxConfig.getNetUrl() + "/h5/reissue", "utf-8");
            menu_a_2.put("url", getAuthorizeUrl(wxConfig.getAppId(), uri2));
            button2.put(menu_a_2);

            //二级菜单 5
            JSONObject menu_a_1 = new JSONObject();
            menu_a_1.put("name", "IPS统计");
            menu_a_1.put("type", "view");
            String uri = URLEncoder.encode(wxConfig.getNetUrl() + "/h5/ipsCom", "utf-8");
            menu_a_1.put("url", getAuthorizeUrl(wxConfig.getAppId(), uri));
            button2.put(menu_a_1);

            menu_a.put("sub_button", button2);
            button.put(menu_a);

            //一级菜单 3
            JSONObject menu_b = new JSONObject();
            menu_b.put("name", "联系客服");
            menu_b.put("type", "click");
            menu_b.put("key", "KE_FU");
            button.put(menu_b);

            big.put("button", button);
            //获取access_token
            String accessToken = getAccessToken(wxConfig);
            //设置请求
            String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
            //执行自定义菜单设置请求
            LogPortal.info("开始执行微信公众号菜单设置，参数[{}]", big.toString());
            JSONObject jsonObject = WxHttpUtil.doPost("平台H5微信公众号菜单设置",url, big.toString());
            LogPortal.info("微信公众号菜单设置成功，接口返回[{}]", jsonObject);
            if (jsonObject != null && 0 == jsonObject.getInt("errcode")) {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            LogPortal.error("微信公众号菜单初始化-菜单uri URLEncoder失败，编码格式错误");
        } catch (Exception e) {
            LogPortal.error("微信公众号菜单初始化-发送[{}]异常,异常信息为[{}]", e.getClass().getSimpleName(), e.getMessage());
        }
        return false;
    }

    private String getAuthorizeUrl(String appId, String uri) {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + uri + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
    }

    /**
     * 通过code获取openid
     *
     * @param code
     * @param config
     * @return
     */
    public String getOpenidByCode(String code, WxConfig config) {
        // 设置网页授权的access_toke的URL
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + config.getAppId() + "&secret=" + config.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
        // 获取网页授权的access_toke、openid等信息
        JSONObject jsonObject = WxHttpUtil.doGet("获取网页授权的access_toke",url);
        LogPortal.info("获取网页授权的access_toke返回信息[{}]", jsonObject.toString());
        String openid = "";
        try {
            openid = jsonObject.get("openid").toString();
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            throw new LogicalException("[{}]通过code获取openid发送[{}]异常，异常信息为[{}]，返回信息为[{}]", traceId,
                    e.getClass().getSimpleName(), e.getMessage(), jsonObject.toString());
        }
        return openid;
    }

    public String sendTemplateMsgNew(WxConfig wxConfig, WxMsg wxMsg) {
        // 获取模板配置

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(wxConfig);
        Map<String, Object> map = new HashMap<>();
        map.put("touser", wxMsg.getOpenid());
        map.put("template_id", wxMsg.getTemplateId());
        map.put("url", "");

        Map<String, Object> miniMap = new HashMap<>();
        miniMap.put("appid", "");
        miniMap.put("pagepath", "");
        map.put("miniprogram", miniMap);

        Map<String, Object> dataMap = new HashMap<>();

        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("value", wxMsg.getFirst());
        firstMap.put("color", "#173177");
        dataMap.put("first", firstMap);

        Map<String, Object> remarkMap = new HashMap<>();
        remarkMap.put("value", wxMsg.getRemark());
        remarkMap.put("color", "#173177");
        dataMap.put("remark", remarkMap);
        if (StringUtils.isNotBlank(wxMsg.getKeyword1())) {
            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value", wxMsg.getKeyword1());
            keyword1.put("color", "#173177");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword1").getString("key"), keyword1);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword2())) {
            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value", wxMsg.getKeyword2());
            keyword2.put("color", "#173177");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword2").getString("key"), keyword2);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword3())) {
            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value", wxMsg.getKeyword3());
            keyword3.put("color", "#173177");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword3").getString("key"), keyword3);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword4())) {
            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value", wxMsg.getKeyword4());
            keyword4.put("color", "#173177");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword4").getString("key"), keyword4);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword5())) {
            Map<String, Object> keyword5 = new HashMap<>();
            keyword5.put("value", wxMsg.getKeyword5());
            keyword5.put("color", "#173177");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword5").getString("key"), keyword5);
        }

        map.put("data", dataMap);

        String data = JSON.toJSONString(map);
        try {
            JSONObject jsonObject = WxHttpUtil.doPost("微信公众号提醒发送".concat(wxMsg.getOpenid()),url, data);
            String errmsg = jsonObject.getString("errmsg");
            int errcode = jsonObject.getInt("errcode");
            if (errcode == 0 && "ok".equals(errmsg)) {
                LogPortal.info("[{}]微信公众号提醒发送成功", wxMsg.getOpenid());
            } else {
                LogPortal.error("[{}]微信公众号提醒发送失败[{}]", wxMsg.getOpenid(), jsonObject.toString());
            }
            return jsonObject.toString();
        } catch (Exception e) {
            LogPortal.error("微信消息发送失败，发生：{}异常，异常信息为：{}", e, e.getClass().getSimpleName(), e.getMessage());
            return null;
        }
    }

    /**
     * 无敌助手消息发送
     * @param wxConfig
     * @param wxMsg
     * @return
     */
    public CommonResult sendWdZhuShouMsgNew(WxConfig wxConfig, WxMsg wxMsg) {
        CommonResult commonResult=new  CommonResult();
        commonResult.setCode(CommonConstants.RETURN_SUCCESS);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(wxConfig);
        Map<String, Object> map = new HashMap<>();
        map.put("touser", wxMsg.getOpenid());
        map.put("template_id", wxMsg.getTemplateId());
        map.put("url", "");

        Map<String, Object> miniMap = new HashMap<>();
        miniMap.put("appid", "");
        miniMap.put("pagepath", "");
        map.put("miniprogram", miniMap);

        Map<String, Object> dataMap = new HashMap<>();

        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("value", wxMsg.getFirst());
        firstMap.put("color", "#FA0E30");
        dataMap.put("first", firstMap);

        Map<String, Object> remarkMap = new HashMap<>();
        remarkMap.put("value", wxMsg.getRemark());
        remarkMap.put("color", "#FA0E30");
        dataMap.put("remark", remarkMap);

        if (StringUtils.isNotBlank(wxMsg.getKeyword1())) {
            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value", wxMsg.getKeyword1());
            keyword1.put("color", "#FA0E30");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword1").getString("key"), keyword1);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword2())) {
            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value", wxMsg.getKeyword2());
            keyword2.put("color", "#FA0E30");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword2").getString("key"), keyword2);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword3())) {
            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value", wxMsg.getKeyword3());
            keyword3.put("color", "#FA0E30");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword3").getString("key"), keyword3);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword4())) {
            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value", wxMsg.getKeyword4());
            keyword4.put("color", "#FA0E30");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword4").getString("key"), keyword4);
        }
        if (StringUtils.isNotBlank(wxMsg.getKeyword5())) {

            Map<String, Object> keyword5 = new HashMap<>();
            keyword5.put("value", wxMsg.getKeyword5());
            keyword5.put("color", "#FA0E30");
            dataMap.put(wxMsg.getConfig().getJSONObject("keyword5").getString("key"), keyword5);
        }

        map.put("data", dataMap);

        String data = JSON.toJSONString(map);
        try {
            JSONObject jsonObject = WxHttpUtil.doPost("微信公众号提醒发送".concat(wxMsg.getOpenid()),url, data);
            String errmsg = jsonObject.getString("errmsg");
            int errcode = jsonObject.getInt("errcode");
            if (errcode == 0 && "ok".equals(errmsg)) {
                LogPortal.info("[{}]微信公众号提醒发送成功", wxMsg.getOpenid());
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "发送成功");
            } else {
                LogPortal.error("[{}]微信公众号提醒发送失败[{}]", wxMsg.getOpenid(), jsonObject.toString());
            }
            return new CommonResult<>(CommonConstants.RETURN_ERROR, jsonObject.toString());
        } catch (Exception e) {
            LogPortal.error("微信消息发送失败，发生：{}异常，异常信息为：{}", e, e.getClass().getSimpleName(), e.getMessage());
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "发送失败,异常信息:"+e.getMessage());
        }
    }
}
